<?php
/**
 * Created by PhpStorm.
 * User: dt
 * Time: 16:53
 */
namespace backend\base;

use yii\web\Controller;
use Yii;
use yii\base\Exception;
use backend\models\jurisdiction\HoPlatformUserInfo;


/**
 * 控制器基类
 * @package app\base
 */
class BaseController extends Controller
{
    //存储request请求体
    public $body = [];
    //存储data
    public $data = [];
    public $title;

    public function beforeAction($action){
        $this->body();
        $route = [//请求路由
           'controller' => $action->controller->id,
           'action' => $action->id,
        ];
        if('/'.$route['controller'].'/'.$route['action'] != '/site/login'){
            if(empty(Yii::$app->cache->get('admin'))){
                header("Location:".'/site/login');die;
            }
        }
       return true;
    }


    /***
     * 存储body体与data数据
     * @return bool
     */
    protected function body()
    {
        if(Yii::$app->request->isPost){
            $this->body=Yii::$app->request->post();
            return true;
        }
        if(Yii::$app->request->isGet){
            $this->body=Yii::$app->request->get();
            return true;
        }
        return false;
    }

    /**
     * 统一JSON返回
     * @param $errIndex
     * @param array $data
     * @return array
     * @throws Exception
     */
    protected function ajaxReturn($errIndex, $data = [])
    {
        if (empty(Yii::$app->params[$errIndex])) {
            $errorMsg = json_encode([
                'code' => Yii::$app->params['params_error']['code'],
                'message' => "未找到返回信息索引[{$errIndex}]",
                'data' => [],
            ],JSON_UNESCAPED_UNICODE);
            throw new Exception($errorMsg);
        }
        $error = Yii::$app->params[$errIndex];
        return [
            'code' => $error['code'],
            'message' => $error['info'],
            'data' => $data
        ];
    }

    /**
     * 统一返回自定义错误信息
     * @param $errIndex
     * @param array $data
     * @return array
     * @throws Exception
     */
    protected function ajaxCustom($code, $error,$data = [])
    {
        return [
            'code' => $code,
            'message' => $error,
            'data' => $data
        ];
    }

    /**
     * 数据安全处理
     * @param     array/string    $data    需要处理的数据
     * @return    array/string    $data    处理后的数据
     */
    public static function parseData($data)
    {
        if(is_array($data)){
            foreach ($data as $k => $v) {
                if(is_array($v)){
                    $data[$k] = self::parseData($v);
                }else if (is_string($v)) {
                    $data[$k] = trim(htmlspecialchars(addslashes($v)));
                }
            }
        }else if (is_string($data)) {
            $data = trim(htmlspecialchars(addslashes($data)));
        }
        return $data;
    }

     /**
     * 获取Web端直传Oss参数
     * @param string $dir
     * @return string
     */
    public static function getOssUpload($dir='image/'){
        function gmt_iso8601($time) {
            $dtStr = date("c", $time);
            $mydatetime = new \DateTime($dtStr);
            $expiration = $mydatetime->format(\DateTime::ISO8601);
            $expiration = substr($expiration, 0, strpos($expiration, '+'));
            return $expiration."Z";
        }
        $end = time()+30;
        $expiration = gmt_iso8601($end);//设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问

        //最大文件大小.用户可以自己设置
        $conditions[] = array(0=>'content-length-range', 1=>0, 2=>1048576000);
        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $conditions[] = array(0=>'starts-with', 1=>'$key', 2=>$dir);

        $base64_policy = base64_encode(json_encode(array('expiration'=>$expiration,'conditions'=>$conditions)));
        $signature = base64_encode(hash_hmac('sha1', $base64_policy, Yii::$app->params['oss']['secret'], true));

        $response = array();
        $response['accessid'] = Yii::$app->params['oss']['key'];
        $response['host'] = Yii::$app->params['oss']['host'];
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;
        return json_encode($response);
    }
}